package base.reflect;


import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.List;

/**
 * @Author Fizz Pu
 * @Date 2021/4/1 下午9:26
 * @Version 1.0
 * 失之毫厘，缪之千里！
 */
class User{
    public int age;
    public String name;

    public void setAge(int age) {
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public User(String name) {
        this.name = name;
    }

    public User() {
    }

    public User(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}


public class InitObject {
    public static void main(String[] args) throws Exception {
        Class<?> class1 = null;
        class1 = Class.forName("base.reflect.User");
        // 第一种方法，实例化默认构造方法，调用set赋值
        User user = (User) class1.newInstance();
        user.setAge(20);
        user.setName("Rollen");
        System.out.println(user);

        // 结果 User [age=20, name=Rollen]
        // 第二种方法 取得全部的构造函数 使用构造函数赋值
        Constructor<?> cons[] = class1.getConstructors();
        // key : cons下标,  value: 参数列表
        Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
        // 查看每个构造方法需要的参数
        for (int i = 0; i < cons.length; i++) {
            Class<?> clazzs[] = cons[i].getParameterTypes();
            List<String> param = new LinkedList<String>();
            for (int j = 0; j < clazzs.length; j++) {
                param.add(clazzs[j].getName());
            }
            map.put(i, param);
        }

        System.out.println(map);

        for (Map.Entry<Integer, List<String>> node: map.entrySet()){
            if(node.getValue().size() == 0){
                user = (User) cons[node.getKey()].newInstance();
                System.out.println(user);
            }

            if(node.getValue().size() == 1){
                user = (User) cons[node.getKey()].newInstance("Rollen");
                System.out.println(user);
            }

            if(node.getValue().size() == 2){
                user = (User) cons[node.getKey()].newInstance(20, "Rollen");
                System.out.println(user);
            }
        }
    }
}
